package com.xudow.app.ui;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.newui.dialog.HeadChoicePop;
import com.xudow.app.newui.zutils.HeadChoiceUtils;
import com.xudow.app.newui.zutils.ZUtils;
import com.xudow.app.ui.task.PortraitUploadTask;
import com.xudow.app.ui.task.StudentAddTask;
import com.xudow.app.util.AlbumUtil;
import com.xudow.app.util.FileUtils;
import com.xudow.app.util.ImageUtils;
import com.xudow.app.util.StringUtils;


import org.springframework.util.support.Base64;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

public class AddNewStudentActivity extends BaseActivity implements View.OnClickListener,
        HeadChoicePop.HeadChoicePopListener {
    private RelativeLayout ico,gender,birthday;
    private ImageView photo;
    private TextView gender_tv,berthday_tv,save;
    private EditText name_ed;

    private static final String TAG = makeLogTag(AddNewStudentActivity.class);
    private static final String TMP_PORTRAIT_PATH = "portrait.png";

    private File tempFile; //拍照获取图片临时文件
    private String IcoPath="";//图片路径
    private int sex=1;//上传性别参数1：男，2：女

    private Uri imageUri=Uri.fromFile(new File(Environment.getExternalStorageDirectory(), TMP_PORTRAIT_PATH));
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_student);
        initview();
        initListener();


    }

    private void initListener() {
        ico.setOnClickListener(this);
        gender.setOnClickListener(this);
        birthday.setOnClickListener(this);
        save.setOnClickListener(this);
        HeadChoicePop.getHeadChoicePopManager().setHeadChoicePopListener(this);
    }

    private void initview() {
        ico=(RelativeLayout)findViewById(R.id.ed_ico_layout);
        gender=(RelativeLayout)findViewById(R.id.ed_gender_layout);
        birthday=(RelativeLayout)findViewById(R.id.ed_berth_layout);
        gender_tv=(TextView)findViewById(R.id.gender_tv);
        berthday_tv=(TextView)findViewById(R.id.berth_tv);
        name_ed=(EditText)findViewById(R.id.ed_name);
        save=(TextView)findViewById(R.id.save_tv);
        photo=(ImageView)findViewById(R.id.student_ico);
    }
    public void goBackClick(View view){
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ed_ico_layout://选择图片
                Log.e("imageuri",""+(null==imageUri));


                ZUtils.hideSoftInput(this);  // 如果软键盘显示 则隐藏
                HeadChoicePop.getHeadChoicePopManager().showPopupWindow(view, this);
                break;
            case R.id.ed_gender_layout://选择性别
                ZUtils.hideSoftInput(this);  // 如果软键盘显示 则隐藏
                final AlertDialog.Builder adlg=new AlertDialog.Builder(this);
                adlg.setTitle("选择性别");
                adlg.setItems(new String[]{"男","女"},new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which){
                        if (which==0){
                            setGender(0);
                            sex=1;
                        }else if(which==1){
                            setGender(1);
                            sex=2;
                        }
                    }
            });
                adlg.create().show();
                break;
            case R.id.save_tv://网络保存
                if (android.text.TextUtils.isEmpty(name_ed.getText())) {

                    getMyApp().makeToast("姓名不能为空");
                    return;
                }
                String cname=name_ed.getText().toString();
                if (android.text.TextUtils.isEmpty(gender_tv.getText())){
                    getMyApp().makeToast("性别不能为空");
                    return;
                }
                if (android.text.TextUtils.isEmpty(berthday_tv.getText())) {
                    getMyApp().makeToast("生日不能为空");
                    return;
                }
                String cbirthday=berthday_tv.getText().toString();
                if (IcoPath.equals("")){
                       getDefIco();
                }
                //TODO 网络请求添加孩子
                HashMap<String,String> pramers=new HashMap<String, String>();
                pramers.put("filePath", IcoPath);
                pramers.put("gender", sex + "");
                try {
                    pramers.put("name",cname);
                    pramers.put("birthday", cbirthday);
                    StudentAddTask addStudentTask=new StudentAddTask(getApplicationContext(),AddHandler);
                    addTask(addStudentTask);
                    addStudentTask.execute(pramers);
                    showLodingDialog("正在处理");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case R.id.ed_berth_layout:
                ZUtils.hideSoftInput(this);  // 如果软键盘显示 则隐藏
                Date date = new Date(System.currentTimeMillis());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);

                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(AddNewStudentActivity.this, dateSetListener, year, month, day).show();

                break;
        }
    }

    /**
     * 获取默认头像
     */
    private void getDefIco() {
        tempFile=new File(getCacheDir().getAbsolutePath(),"child_ico.png");
        Bitmap btp;
        if (sex==1){
            btp= BitmapFactory.decodeResource(getResources(),R.mipmap.boy);
        }else {
            btp= BitmapFactory.decodeResource(getResources(),R.mipmap.gril);
        }
        try {
            btp.compress(Bitmap.CompressFormat.JPEG, 100, new BufferedOutputStream(new FileOutputStream(tempFile)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        IcoPath=tempFile.getAbsolutePath();
    }

    public void setGender(int a){
        if (a==0)
            gender_tv.setText("男");
        else
            gender_tv.setText("女");
    }
    /**
     * 生日选择
     */
    private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            String birth = String.format("%s-%s-%s", year+"", getTime(monthOfYear+1), getTime(dayOfMonth));
            berthday_tv.setText(birth);

        }

    };
    private String getTime(int t){
        if (t<10)
            return "0"+t;
        else
            return t+"";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (RESULT_OK != resultCode) {
            return;
        }

        if (requestCode == TAKE_PICTURE_REQUEST_CODE && resultCode == RESULT_OK) { // 剪切拍照的图片

            if (imageUri == null) {
                Toast.makeText(this, "图片路径出错", Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                int orentation= ZUtils.readPictureDegree(imageUri.getPath());

                if(0!=orentation) {
                    Log.e("旋转角度", orentation + "");
                    Bitmap bmp = HeadChoiceUtils.getBitmapFormUri(this,imageUri);
                    Bitmap rotatbmp=ZUtils.rotaingImageView(orentation,bmp);
                    rotatbmp.compress(Bitmap.CompressFormat.PNG,100,
                            new FileOutputStream(new File(imageUri.getPath())));
                    bmp.recycle();
                    rotatbmp.recycle();
                }
                HeadChoiceUtils.getInstance().cropImageUri(this, imageUri, 200, 200, CROP_PICTURE_REQUEST_CODE, imageUri);
            } catch (Exception e) {
            }

        } else if (requestCode == PHOTO_REQUEST_CODE && resultCode == RESULT_OK) { // 剪切相册图片

            if (data != null) {
                Uri photoUri = data.getData();
                if (photoUri == null) {
                    Toast.makeText(this, "图片路径出错", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    HeadChoiceUtils.getInstance().cropImageUri(this, photoUri, 200, 200, CROP_PICTURE_REQUEST_CODE, imageUri);
                } catch (Exception e) {
                }
            }

        } else if (requestCode == CROP_PICTURE_REQUEST_CODE && resultCode == RESULT_OK) { // 显示剪切后的图片

            String imagePath = "file://" + imageUri.getPath();
            IcoPath=imageUri.getPath();
            try {
                Bitmap bmp=HeadChoiceUtils.getBitmapFormUri(this,Uri.parse(imagePath));
                photo.setImageBitmap(bmp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * 添加孩子网络保存Handler
     */
    private Handler AddHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();
            String message;
            if (PortraitUploadTask.SUCCESS == msg.what) {
                 message = "添加成功";
               /* Intent intent =new Intent(AddNewStudentActivity.this,ChoseChildActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);*/
                setResult(2);
                finish();
            } else {
                 message = "添加失败";
            }
            getMyApp().makeToast(message);

        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        //deleleTmpPortrait();
    }

    /**
     * 删除临时头像
     */
    private void deleleTmpPortrait() {
        String path =  imageUri.getPath();
        Log.e("path",path);
        if (new File(path).exists()) {
            new File(path).delete();
        }
    }

    private static final int TAKE_PICTURE_REQUEST_CODE = 80;
    private static final int CROP_PICTURE_REQUEST_CODE = 81;
    private static final int PHOTO_REQUEST_CODE = 82;

    /**
     * 打开照相机
     */
    @Override
    public void openCamera() {
        HeadChoiceUtils.getInstance().openCamera(this, TAKE_PICTURE_REQUEST_CODE, imageUri);
        HeadChoicePop.getHeadChoicePopManager().dismissPopWindow(this);

    }

    /**
     * 打开相册
     */
    @Override
    public void openPhoto() {
        HeadChoiceUtils.getInstance().openPhoto(this, PHOTO_REQUEST_CODE);
        HeadChoicePop.getHeadChoicePopManager().dismissPopWindow(this);
    }
}
